﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.API.Application.Command.RoleMenu;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.RoleMenu
{
    public class GetMenuTreeHandler : IRequestHandler<GetMenuTreeCommand, APIResult<List<Tree>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;

        public GetMenuTreeHandler(IBaseRepository<MenuModel> menuRepo)
        {
            this.menuRepo = menuRepo;
        }
        public Task<APIResult<List<Tree>>> Handle(GetMenuTreeCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<Tree>> result = new APIResult<List<Tree>>();
            result.Message = "显示父级菜单成功";
            result.Code = APIEnum.Ok;
            result.Data = GetMenu(request.pid);
            return Task.FromResult(result);
        }
        public List<Tree> GetMenu(long pid)
        {
            var query = menuRepo.GetAll().Where(x => !x.IsDel && x.ParentId == pid).ToList();
            List<Tree> result = new List<Tree>();
            foreach (var item in query)
            {
                result.Add(new Tree
                {
                    id = item.Id,
                    label = item.MenuName,
                    children = GetMenu(item.Id)
                });
            }
            return result;
        }
    }
}
